package gov.kqqzyyy.monkey.tjpd.mytools;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.InputStream;
import java.util.Date;

import gov.kqqzyyy.monkey.tjpd.broadcast.DownLoadReceiver;
import gov.kqqzyyy.monkey.tjpd.objects.TJ_ZSXX;
import gov.kqqzyyy.monkey.tjpd.ui.SplashActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MyBaseActivity extends AppCompatActivity {

    private ProgressDialogFragment progressDialogFragment;

    private MyApplication myApplication;
    private SharedPreferences mySharedPreferences;
    private DownLoadReceiver downLoadReceiver;

    private Call<String> systemTimeCall;
    private Call<String> zsxxCall;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myApplication = (MyApplication) getApplication();
        mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        downLoadReceiver = new DownLoadReceiver();
        IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        this.registerReceiver(downLoadReceiver, intentFilter);

        IntentFilter restartFilter = new IntentFilter();
        restartFilter.addAction(Intent.ACTION_TIME_TICK);
//        registerReceiver(SystemTimeReceiver, restartFilter);
    }

    @Override
    protected void onStop() {
        super.onStop();
//        unregisterReceiver(SystemTimeReceiver);
        if (systemTimeCall != null) {
            systemTimeCall.cancel();
        }
        if (zsxxCall != null) {
            zsxxCall.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(downLoadReceiver);
        System.gc();
    }

    protected MyApplication getMyApplication() {
        return myApplication;
    }

    protected SharedPreferences getMySharedPreferences() {
        return mySharedPreferences;
    }

    public void cancelProgressDialog() {
        if (progressDialogFragment != null && progressDialogFragment.getDialog() != null) {
            progressDialogFragment.getDialog().dismiss();
        }
    }

    protected void showProgressDialog(String message) {
        cancelProgressDialog();
        progressDialogFragment = new ProgressDialogFragment();
        progressDialogFragment.setMessage(message);
        progressDialogFragment.show(getFragmentManager(), "downLoading");

    }

    protected Bitmap readBitMap(int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        //获取资源图片
        InputStream is = getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    protected boolean isDebug() {
        return getApplicationInfo() != null &&
                (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
    }

    protected boolean isRestartTime() {
        Date localDateTime = new Date(System.currentTimeMillis());
        localDateTime.setTime(localDateTime.getTime() + getMyApplication().getDeltaTime());
        String timeNow = DateUtil.getDFFormatString(localDateTime);
        return timeNow.compareTo("23:59:55") > 0 || timeNow.compareTo("00:00:05") < 0 || (timeNow.compareTo("11:59:55") > 0 && timeNow.compareTo("12:00:05") < 0);
    }

    public void doGetServerTime() {
        systemTimeCall = MyServiceUtil.getSystemTimeCall();
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                String result = response.body();
                if (result != null) {
                    result = result.replace("\"", "");
                    result = result.replaceAll("T", " ");
                    Date serverDate = DateUtil.getDTFormatDateTime(result);
                    if (serverDate != null) {
                        long deteDelta = serverDate.getTime() - new Date(System.currentTimeMillis()).getTime();
                        myApplication.setDeltaTime(deteDelta);
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "获取服务器时间出错：" + t.toString(), Toast.LENGTH_SHORT).show();
            }
        };
        systemTimeCall.enqueue(callback);
    }

    private BroadcastReceiver SystemTimeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                if (isRestartTime()) { //次日、11点 重启
                    new CountDownTimer(5000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                        }

                        @Override
                        public void onFinish() {
                            Intent intent1 = new Intent(getApplicationContext(), SplashActivity.class);
                            startActivity(intent1);
                            finish();
                        }
                    }.start();
                }
            }
        }
    };


    protected void doSetZsxx(TJ_ZSXX tjZsxx) {

    }

    //获取诊室信息
    protected void doGetZsxx(int zsid) {
        zsxxCall = MyServiceUtil.getZsxxCall(zsid);
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(@NonNull Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                String result = response.body();
//                if (result != null && !result.equals(zsxxResult)) {
//                    zsxxResult = result;
                TJ_ZSXX tjZsxx = gson.fromJson(result, new TypeToken<TJ_ZSXX>() {
                }.getType());
//                if (tjZsxx != null) {
                doSetZsxx(tjZsxx);
//                    String dqhText = tjZsxx.getDqh() + "";
//                    currentNum.setText(dqhText);
//                    patientNum.setText(tjZsxx.getDqbh());
//                    patientName.setText(MyStringUtil.doHideName(tjZsxx.getDqry()));
//                    if (loadQRCode) {
//                        loadQRCode = false;
//                        Uri uri = Uri.parse(tjZsxx.getImgurl());
//                        qrCodeImg.setImageURI(uri);
//                    }
//                    if (tjZsxx.getHj() == 0) {
//                        doCallPatient(tjZsxx);
//                    }else {
//                        timeToGetInfo(1);
//                    }
//                } else {
//                    timeToGetInfo(1);
//                }
            }

            @Override
            public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
//                timeToGetInfo(1);
                doSetZsxx(null);
            }
        };
        zsxxCall.enqueue(callback);
    }
}
